#include <os/sleep.h>
#include <os/task.h>
#include <os/clock.h>
#include <os/timer.h>
#include <sys/time.h>
#include <os/schedule.h>
#include <os/mp.h>

static void TaskSleepTimeoutHandler(timer_t *timer,task_t *task)
{
    //list_del(&task->list);
    TaskWakeUp(task);
}

uint64_t TaskSleepByTicks(clock_t ticks)
{
    task_t *cur;
    timer_t *timer;
    uint64_t delta_ticks;

    if (!ticks)
        return 0;

    cur = cur_task;
    if (!cur)
        return 0;
    
    KPrint("task sleep by ticks called %x\n",cur);
    timer = &cur->sleep_time;
    // set timer
    TimerModify(timer, ticks);
    TimerSetArgument(timer, cur);
    // register timeout handler
    TimerSetHandler(timer, TaskSleepTimeoutHandler);
    TimerAdd(timer);
    InterruptEnable();
    TaskBlock(TASK_BLOCKED); // task block
   
    uint32_t eflags=InterruptDisableStore();
    // timer timeout
    if (timer->timeout > timer_ticks)
    {
        delta_ticks = timer->timeout - timer_ticks;
        TimerDel(timer);
    }
    InterruptEnableRestore(eflags);
    KPrint("task sleep %d ticks\n",delta_ticks);
    return delta_ticks;
}

//SysSleep function: task sleep given second,and create a sleep timer
uint32_t SysSleep(uint32_t second)
{
#ifdef ENABLE_SMP
    clock_t ticks = second * CurTimerFrequery;
#else
    clock_t ticks = second * HZ;
#endif
    if (!second)
        return 0;
    second = do_div64(TaskSleepByTicks(ticks),second);
    return second;
}